package com.example.springbootdemo.controller;

import com.example.springbootdemo.bean.Goods;
import com.example.springbootdemo.mapper.GoodsMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class GoodsController{
    @Autowired
    GoodsMapper goodsMapper;

    @RequestMapping("/GoodsManager")
    public String goodsManager(Integer id, String name, Integer minPrice, Integer maxPrice, String order, HttpServletRequest request){
        Goods goods = new Goods();
        if (name == null || name.equals("")){
            goods.setName("");
        }
//            已在mapper中like通过concat加上%%
        goods.setName(name);
        goods.setId(id);
        List<Goods> goodsList = goodsMapper.SelectGoods(goods,minPrice,maxPrice,order);
        request.setAttribute("goodsList", goodsList);
        return "GoodsManager";
    }

    @RequestMapping("/SelectGoods")
    public String SelectGoods(HttpServletRequest request, HttpServletResponse response){
        List<Goods> goodsList = goodsMapper.selectAll();
        request.setAttribute("goodsList", goodsList);
        return "SelectGoods";
    }

    @RequestMapping("/ToAddGoods")
    public String ToAddGoods(){
        return "AddGoods";
    }

    @RequestMapping("/AddGoods")
    public String AddGoods(Goods goods, MultipartFile file) throws IOException {
//        用户上传了文件才会执行文件上传的相关代码
        if (!file.isEmpty()){
            //        修改文件名，保证文件名不会重复
            String oldName = file.getOriginalFilename();    //获取文件上传的原名
//        截取保留上传文件的原名
            String ext = oldName.substring(oldName.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();//随机生成一个不重复的String
            String fileName = uuid+ext;
//        上传路径
            String pre = "/Users/erolaffy/IdeaProjects/SpringBootDemo/uploadImages/";
            String filePath = pre+fileName;
            file.transferTo(new File(filePath));    //复制用户上传的文件到指定位置
            goods.setImgsrc("/images/"+fileName);   //在数据库中使用相对路径

        }
        goodsMapper.insertGoods(goods);
        return "hello";
    }
}